package love.yuanmengrobot.springmvcdemo2.controller;



import love.yuanmengrobot.springmvcdemo2.pojo.SysRole;
import love.yuanmengrobot.springmvcdemo2.pojo.SysUser;
import love.yuanmengrobot.springmvcdemo2.service.RoleService;
import love.yuanmengrobot.springmvcdemo2.service.UserService;
import love.yuanmengrobot.springmvcdemo2.utils.*;
import love.yuanmengrobot.springmvcdemo2.vo.RoleVo;
import love.yuanmengrobot.springmvcdemo2.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    String str1;
    String str2;
    /**
     * 查询所有的 及模糊查询
     *
     * @param userVo
     * @return
     */
    @RequestMapping("/loadAllUser")
    public DataGridView loadAllUser(UserVo userVo) {
        return this.userService.queryAllUser(userVo);
    }




    /**
     * 查询所有的 及模糊查询
     *
     * @param userVo
     * @return
     */
    @RequestMapping("/loadAllAdministrators")
    public DataGridView loadAllAdministrators(UserVo userVo) {
        return this.userService.queryAllAdministrators(userVo);
    }


    /**
     * 添加用户
     *
     * @param userVo
     * @return
     */
    @RequestMapping("/addUser")
    public ResultObj addUser(UserVo userVo) {
        try {
            this.userService.addUser(userVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }


    @RequestMapping("/batchAddUserData")
    @Transactional
    public ResultObj upload(HttpServletRequest request, Integer pid2, MultipartFile uploadUserData) throws Exception {
        try {
            System.out.println("star");
            UserVo userVo = new UserVo();
            Integer[] ids=new Integer[1];
            ids[0]=4;
            SysUser user;


            // 获取文件名
            String fileName = uploadUserData.getOriginalFilename();
//            // 获取文件后缀
            String prefix = fileName.substring(fileName.lastIndexOf("."));
            File excelFile = null;
//
            try {
                // 用时间作为文件名，防止生成的临时文件重复
                excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
                uploadUserData.transferTo(excelFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String str = excelFile.getAbsolutePath().replace("\\", "\\\\");
            ReadExcel rd = new ReadExcel();
            List<List<Object>> lob = rd.readExcel(new File(str));

            for (int i = 0; i < lob.size(); i++) {
                List<Object> lo = lob.get(i);

                user =userService.queryUserLoginnameAndUserid(String.valueOf(lo.get(0)).trim());
                if(null!=user){
                    continue;
                }
                userVo.setLoginname(String.valueOf(lo.get(0)).trim());
                userVo.setRealname(String.valueOf(lo.get(1)).trim());

                this.userService.addUser(userVo);
                user =userService.queryUserLoginnameAndUserid(String.valueOf(lo.get(0)).trim());
                this.userService.saveSelectRole(user.getUserid(), ids);
            }
            new File(str).delete();
            return ResultObj.ImportExcel_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ImportExcel_ERROR;
        }
    }


    /**
     * 修改用户
     *
     * @param userVo
     * @return
     */
    @RequestMapping("/updateUser")
    public ResultObj updateUser(UserVo userVo) {

        try {
            this.userService.updateUser(userVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteUser")
    public ResultObj addUser(Integer id) {
        try {
            this.userService.deleteUser(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 重置用户密码
     *
     * @param id
     * @return
     */
    @RequestMapping("/resetPwdUser")
    public ResultObj resetPwdUser(Integer id) {
        try {
            this.userService.resetPwdUser(id);
            return ResultObj.RESET_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.RESET_ERROR;
        }
    }

    /**
     * 将中文转换为拼音
     *
     * @param username
     * @return
     */
    @RequestMapping("/usernameChineseToPinYin")
    public Map<String, Object> usernameChineseToPinYin(String username) {
        Map<String, Object> map = new HashMap<>();
        String pingYin = ChineseToPinYinUtils.getPingYin(username);
        map.put("value", pingYin);
        return map;
    }

    @RequestMapping("/userRoleTableInit")
    public DataGridView userRoleTableInit(Integer id) {
        //1.查询所有的角色]
        RoleVo roleVo = new RoleVo();
        roleVo.setAvailable(SystemConstant.AVAILABLE_TRUE);
        List<Map<String, Object>> allRole = this.roleService.queryAllRoleForList(roleVo);
        //2.当前用户拥有哪些角色
        List<SysRole> currentUser = this.userService.queryUserHaveRole(id);
        //比较两者 标记出当前用户的角色
        if (null != currentUser && currentUser.size() > 0) {
            for (Map<String, Object> map : allRole) {
                boolean LAY_CHECKED = false;
                Integer roleId = (Integer) map.get("roleid");
                for (SysRole role : currentUser) {
                    if (role.getRoleid() == roleId) {
                        LAY_CHECKED = true;
                        break;
                    }
                }
                map.put("LAY_CHECKED", LAY_CHECKED);
            }
        }
        return new DataGridView(Long.valueOf(allRole.size()), allRole);
    }

    /**
     * 保存分配的角色
     *
     * @param uid
     * @param ids
     * @return
     */
    @RequestMapping("/saveSelectRole")
    public ResultObj saveSelectRole(Integer uid, Integer[] ids) {
        try {
            this.userService.saveSelectRole(uid, ids);
            return ResultObj.DISPATCH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DISPATCH_ERROR;
        }
    }


    /**更改用户密码
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */

    @RequestMapping("/changePwd")
    public ResultObj changePwd(String oldPassword,String newPassword) {
        try {

            SysUser user = (SysUser) WebUtils.getHttpSession().getAttribute("user");
            str1=new String(DigestUtils.md5DigestAsHex(oldPassword.getBytes()).getBytes(),"utf-8");
            str2=new String(user.getPwd().getBytes(),"utf-8");

            if(str1.equals(str2)!=true){ //判断旧密码是否和数据库中的密码相等
                return ResultObj.OldPwd_Error;
            }

            user.setPwd(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
            userService.updateUser2(user);
            return ResultObj.OPERATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.OPERATE_ERROR;
        }
    }

}
